<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2021/08/27} {10:35} 
 */

namespace wanghua\general_utility_tools_php\framework\base;

use wanghua\general_utility_tools_php\framework\BaseController;
use think\Exception;
use think\Request;
use wanghua\general_utility_tools_php\tool\Tools;

/**
 * 基础权限架构
 * Class BaseAuthController
 * @package library\framework\base
 */
class BaseAuthController extends BaseController
{

    public $debug = false;
    //权限错误重定向URL
    protected $auth_err_redirect_url = '/index/err/fail';
    public function __construct()
    {
        parent::__construct();


        $err_redirect_url = config('service_framework_config.auth_err_redirect_url');
        if($err_redirect_url){
            $this->auth_err_redirect_url = $err_redirect_url;
        }

    }

    /**
     * desc：默认鉴权
     * author：wh
     * @return bool
     */
     function defaultAuth(){
        $params = input();
        if(empty($params['nonce'])){
            Tools::log_to_write_txt(['服务被拒绝，鉴权参数缺失:nonce。params'=>input()]);
            //跳转至错误中转控制器
            return $this->response($this->auth_err_redirect_url,['title'=>'服务被拒绝. permission denied']);
        }
        if(empty($params['timestamp'])){
            Tools::log_to_write_txt(['服务被拒绝，鉴权参数缺失:timestamp。params'=>input()]);
            //跳转至错误中转控制器
            return $this->response($this->auth_err_redirect_url,['title'=>'服务被拒绝. permission denied.']);
        }
        if(empty($params['sign'])){
            Tools::log_to_write_txt(['服务被拒绝，鉴权参数缺失:sign。params'=>input()]);
            //跳转至错误中转控制器
            return $this->response($this->auth_err_redirect_url,['title'=>'服务被拒绝. permission denied。']);
        }
        $sign = $params['sign'];
        unset($params['sign']);
        if(Tools::signature($params) != $sign){

            Tools::log_to_write_txt(['签名失败，服务被拒绝.'=>input()]);

            //跳转至错误中转控制器
            return $this->response($this->auth_err_redirect_url,['title'=>'服务被拒绝. permission denied!']);
        }
        return true;
    }
    protected function response($url,$params){

        if(Request::instance()->isAjax() || Request::instance()->isPost()){
            return json(Tools::set_res(500,$params['title'],['url'=>$url]));
        }
        //跳转至错误中转控制器
        return $this->redirect(url($url,$params));
    }
}